package com.eqs.enterprisequestionnaire.controller;

import com.eqs.enterprisequestionnaire.model.pojo.User;
import com.eqs.enterprisequestionnaire.result.R;
import com.eqs.enterprisequestionnaire.service.EmailService;
import com.eqs.enterprisequestionnaire.service.UserService;
import com.eqs.enterprisequestionnaire.tool.VerificationCodeGenerator;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.ExpiredSessionException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private EmailService emailService;

    //查看用户信息，通过id
    @GetMapping("/detailById/{id}")
    public R<User> detailById(@PathVariable Integer id){
        return R.success(userService.getById(id));
    }
    @GetMapping("/detailByName/{name}")
    public R<User> detailByName(@PathVariable String name){
        return R.success(userService.selectByUserName(name));
    }
    //添加用户,用于注册
    @PostMapping("/addUser")
    public R<User> add(@RequestBody User user){
        if(userService.selectByUserName(user.getUserName())!=null)
            return R.error("重复用户名");
        else{
            userService.registerUser(user);
            return R.success("添加用户成功");
        }
    }
    // 登录
    @PostMapping("/login")
    public R<String> login(@RequestParam String userName, @RequestParam String password) {
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated())
            return R.success("用户已登录");
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        token.setRememberMe(true);
//可以通过前端传回地址
        int a=1;
        try {
            subject.login(token);
            userService.refreshLogin(userName,password);
            return R.success("登录成功");
        } catch (UnknownAccountException uae) {
            return R.error("未知账户");
        } catch (IncorrectCredentialsException ice) {
            return R.error("密码不正确");
        } catch (LockedAccountException lae) {
            return R.error("账户已锁定");
        } catch (ExpiredSessionException ese) {
            // 处理会话过期异常
            return R.error("会话已过期，请重新登录");
        } catch (AuthenticationException ae) {
            return R.error("登录失败: " + ae.getMessage());
        }
    }

    //修改个人信息
    @PutMapping("/editUserInfo") //可以在@RequestBody后面添加@Valid来运作user的格式判断
    public R<String> editUser(@RequestBody User user){
        userService.updateUser(user);
        return R.success("修改成功");
    }

    //删除用户
    @DeleteMapping("/deleteUser/{id}")
    public R<String> deleteUser(Integer id){
        boolean b = userService.removeById(id);
        if(b){
            return R.success("删除用户成功");
        }
        else
            return R.error("无用户可删除？");
    }

    //重设密码
    @PostMapping("/resetPassword")
    public R<String> resetPassword(@RequestParam Integer userId,
                                   @RequestParam String newPassword) {
        userService.updatePassword(userId,newPassword);
        return R.success("密码重设成功");
}

//忘记密码
@PostMapping("/forgot/{userId}")
public R<String> forgotPassword(@PathVariable Integer userId) {
    User user = userService.selectById(userId);
    String email = user.getEmail();
    if (user == null) {
        return R.error("未能找到用户");
    }

    String verificationCode = VerificationCodeGenerator.generateCode();
    // 保存验证码到用户表或缓存
    userService.saveVerificationCode(email, verificationCode);

    emailService.sendSimpleMessage(email, "Password Reset Verification Code", "Your verification code is: " + verificationCode);

    return R.success(verificationCode);
}
@PostMapping("/logout")
public R logout(){
    Subject subject=SecurityUtils.getSubject();
    if(subject.isAuthenticated()) {
        subject.logout();
        return R.success("退出登录");
    }
    return R.error("退出失败");
}


 //示例：需要特定权限才能访问的接口
    @GetMapping("/secureData")
    @RequiresRoles("admin")
    public R<String> secureData() {
        return R.success("查看数据权限");
    }
}
